//
//  HomeViewController.m
//  YXFinance
//
//  Created by uplooking on 2018/10/22.
//  Copyright © 2018年 CRLong. All rights reserved.
//

#import "HomeViewController.h"

@interface HomeViewController ()
<
SDCycleScrollViewDelegate,
UITableViewDataSource,
UITableViewDelegate,
DZNEmptyDataSetDelegate,
DZNEmptyDataSetSource
>
{
    NSMutableArray * arrayURLSlide;
    NSMutableArray * arraySlider;
    NSInteger mTag;
    UITableView *tableView;
    NSMutableArray *arrayResult;
    BOOL isLoading;
    BOOL isCanLoadMore;
    ListLoadingFooterView *vListLoading;
    UIView *vListFooterNone;
    NSInteger page;
    NSInteger row;
    FindMidChooseView * topView;
    SDCycleScrollView * sySlider;
    UILabel * totalLabel;
    CGFloat mHeight;
    BOOL isWebFinish;
    UIView * applyView;
}


@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"研选财经";
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:HexRGBA(0xa18964, 1), NSFontAttributeName:[UIFont systemFontOfSize:20 * kAutoScanleX]}];
    
    
    [self setBackRightBarButtonItemAction:@selector(shareAction:) image:[UIImage imageNamed:@"icon_fenxiang"]];
    [self initFirstView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoData) name:REFRESH_USER_INFO object:nil];
    
}

#pragma mark -- 判断时候有网络
- (void)initFirstView{
    
    WS(weakSelf);
    
    if (UserCenterHelper.checkNetWork) {
        
        NoNetWorkView * noWorkView=[[NoNetWorkView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        [ApplicationDelegate.window addSubview:noWorkView];
        [noWorkView setBackgroundColor:[UIColor whiteColor]];
        [noWorkView setBlockNetWork:^{
            [weakSelf initAppHomeUpView];
        }];
        
    }else{
        
        [self initAppHomeUpView];
    }
    
}

# pragma mark -- 分享
- (void)shareAction:(UIButton *)sender{
    
    [self setShareSDKImage:[UIImage imageNamed:@"homeShare"] text:@"人生就像滚雪球，需要很湿的雪，需要很长的坡。我们在寻找，可能会成为下一个中国巴菲特的你。" title:@"寻找中国巴菲特-第五季" url:[NSURL URLWithString:@"http://bafeite.tvlicai.com"]];
    
}


- (void)initAppHomeUpView{
    
    mTag = 0;
    row = 10;
    isLoading = YES;
    isWebFinish = NO;
    mHeight = 100 * kAutoScanleX;
    arrayURLSlide = [NSMutableArray array];
    arraySlider = [NSMutableArray array];
    arrayResult=[NSMutableArray arrayWithCapacity:0];
    
    [self initView];
    [self startSKV];
    [self getUserInfoData];
    [self getConfigureEnrollsData];
    [self getBannerData];
    [self getHomeListData];
    [self setUpdateView];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    if (!UserCenterHelper.checkNetWork) {
        
        [self getConfigureEnrollsData];
    }
}


- (void)initView{
    
    applyView = [[UIView alloc]init];
    [applyView setClipsToBounds:YES];
    [self.view addSubview:applyView];
    [applyView setBackgroundColor:[UIColor whiteColor]];
    [applyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.mas_equalTo(0);
    }];
    
    tableView = [[UITableView alloc] init];
    [tableView setBackgroundColor:[UIColor clearColor]];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [tableView setShowsHorizontalScrollIndicator:NO];
    [tableView setShowsVerticalScrollIndicator:NO];
    [tableView setEmptyDataSetDelegate:self];
    [tableView setEmptyDataSetSource:self];
    [self.view addSubview:tableView];
    tableView.mj_header = [ZNDIYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getHomeListData)];
    [tableView registerClass:[TeacherIndexCell class] forCellReuseIdentifier:@"TeacherIndexCell"];
    [tableView registerClass:[ImageTextIndexTableViewCell class] forCellReuseIdentifier:@"ImageTextIndexTableViewCell"];
    [tableView registerClass:[HomeWebCell class] forCellReuseIdentifier:@"HomeWebCell"];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(applyView.mas_top);
    }];
    
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getHomeListPageData)];
    [tableView.mj_footer beginRefreshing];
    
    
    UIButton * applyBtn=[[UIButton alloc]init];
    [applyBtn setBackgroundColor:HexRGBA(0xb99c6d, 1)];
    [applyBtn addTarget:self action:@selector(fBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [applyBtn.layer setMasksToBounds:YES];
    [applyBtn.layer setCornerRadius:8.0 * kAutoScanleX];
    [applyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [applyBtn setTitle:@"立即报名" forState:UIControlStateNormal];
    [applyBtn.titleLabel setFont:[UIFont systemFontOfSize:16 * kAutoScanleX]];
    [applyView addSubview:applyBtn];
    [applyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(applyView);
        make.height.mas_equalTo(45 * kAutoScanleX);
        make.centerX.equalTo(applyView);
        make.width.mas_equalTo(576/2.0 * kAutoScanleX);
    }];
    
    
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,330 * kAutoScanleX)];
    [headerView setBackgroundColor:[UIColor whiteColor]];
    [tableView setTableHeaderView:headerView];

    
    sySlider = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0,kScreenWidth, 195 * kAutoScanleX) delegate:self placeholderImage:[UIImage imageNamed:@"img_home_banner_morentu"]];
    sySlider.currentPageDotColor = [UIColor redColor];
    sySlider.autoScrollTimeInterval = 5;
    sySlider.pageControlBottomOffset = 30 * kAutoScanleX;
    sySlider.pageDotColor = [UIColor whiteColor];
    [sySlider.layer setMasksToBounds:YES];
    [headerView addSubview:sySlider];
    
    
    UIView * vTop = [[UIView alloc]init];
    [vTop setBackgroundColor:HexRGBA(0xeeeeee, 1)];
    [headerView addSubview:vTop];
    [vTop mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.greaterThanOrEqualTo(self.view.mas_top).priority(1000);
        make.top.equalTo(headerView).offset(280 * kAutoScanleX).priority(500);
        make.left.right.equalTo(headerView);
        make.height.mas_equalTo(50 * kAutoScanleX);
    }];
    
    WS(weakSelf);
    topView=[[FindMidChooseView alloc]initWithFrame:CGRectMake(20 * kAutoScanleX, 0, kScreenWidth - 40 * kAutoScanleX, 50 * kAutoScanleX)];
    [topView setBackgroundColor:HexRGBA(0xeeeeee, 1)];
    topView.arrayTopTitle = @[@"导师阵容",@"活动规则",@"精彩看点"];
    [topView setTextNormalColor:HexRGBA(0x2e2e2e, 1)];
    [topView setTextSelectedColor:HexRGBA(0xb99c6d, 1)];
    [topView setHkWidth:60 * kAutoScanleX];
    [topView setHkColor:HexRGBA(0xb99c6d, 1)];
    [vTop addSubview:topView];
    [topView setClickAction:^(NSInteger tag){
        [weakSelf setTopTag:tag];
    }];
    
    UIImageView * applyImageView = [[UIImageView alloc]init];
    [applyImageView setImage:[UIImage imageNamed:@"bg_liji_baoming"]];
    [applyImageView setUserInteractionEnabled:YES];
    [headerView addSubview:applyImageView];
    [applyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(topView.mas_top).offset(-15 * kAutoScanleX);
        make.centerX.equalTo(headerView);
        make.size.mas_equalTo(CGSizeMake(350 * kAutoScanleX, 99 * kAutoScanleX));
    }];
    
    UIButton * fBtn=[[UIButton alloc]init];
    [fBtn setBackgroundColor:HexRGBA(0xc61d19, 1)];
    [fBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [fBtn addTarget:self action:@selector(fBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [fBtn setTitle:@"立即报名" forState:UIControlStateNormal];
    [fBtn.titleLabel setFont:[UIFont systemFontOfSize:14 * kAutoScanleX]];
    [fBtn.layer setMasksToBounds:YES];
    [fBtn.layer setCornerRadius:8/2.0 * kAutoScanleX];
    [applyImageView addSubview:fBtn];
    [fBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(applyImageView).offset(-17.5 * kAutoScanleX);
        make.centerX.equalTo(applyImageView);
        make.size.mas_equalTo(CGSizeMake(100 * kAutoScanleX, 34 * kAutoScanleX));
    }];
    
    
    totalLabel = [[UILabel alloc]init];
    [totalLabel setTextColor:HexRGBA(0x000000, 1)];
    [totalLabel setFont:[UIFont systemFontOfSize:14 * kAutoScanleX]];
    [totalLabel setTextAlignment:NSTextAlignmentLeft];
    [applyImageView addSubview:totalLabel];
    [totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(applyImageView);
        make.bottom.equalTo(fBtn.mas_top).offset(-12 * kAutoScanleX);
    }];
    
}

#pragma mark--tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger count=[arrayResult count];
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (mTag == 0) {
        
        static NSString *identifier = @"TeacherIndexCell";
        TeacherIndexCell * cell = [_tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        TeacherIndexModel *model = arrayResult[indexPath.row];
        [cell setModel:model];
        return cell;
        
    }else if (mTag == 1){
        
        static NSString * identifier = @"HomeWebCell";
        HomeWebCell * cell = [_tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSString * url = arrayResult[indexPath.row];
        [cell setUrl:url];
        [cell setBlockWebHeight:^(CGFloat height) {
            if (!isWebFinish) {
                mHeight = height;
                isWebFinish = YES;
                [tableView reloadData];
            }
        }];
        
        return cell;
        
    }else if (mTag == 2){
        
        static NSString *identifier = @"ImageTextIndexTableViewCell";
        ImageTextIndexTableViewCell * cell = [_tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NewsIndexModel *model=arrayResult[indexPath.row];
        [cell setModel:model];
        return cell;
        
    }
    
    return nil;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (mTag == 0) {
        
        return 100 * kAutoScanleX;
        
    }else if (mTag == 1){
        
        return mHeight;
        
    }else if (mTag == 2){
        
        return 100 * kAutoScanleX;
    }
    
    return 100 * kAutoScanleX;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (mTag == 0) {
        
        TeacherIndexModel * model = arrayResult[indexPath.row];
        
        TeamRandomDetailsViewController * vc = [[TeamRandomDetailsViewController alloc]init];
        vc.teacher_id = model.t_id;
        [[BaseTabBarViewController shareInstance].navigationController pushViewController:vc animated:YES];
        
    }else if (mTag == 2){
        
        NewsIndexModel * model = arrayResult[indexPath.row];
        
        InformationDetailsViewController * vc = [[InformationDetailsViewController alloc]init];
        vc.n_id = model.n_id;
        [[BaseTabBarViewController shareInstance].navigationController pushViewController:vc animated:YES];
        
    }
    
}

#pragma mark -- 切换
- (void)setTopTag:(NSInteger)tag{
    
    mTag = tag;
    
    [arrayResult removeAllObjects];
    [self showHudInView:self.view hint:@""];
    [self getHomeListData];
    
    [applyView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(mTag == 1 ? 70 * kAutoScanleX : 0);
    }];
    
}

#pragma mark -- 立即报名
- (void)fBtnAction:(UIButton *)sender{
    
    WS(weakSelf);
    //判断是否登录，没登录跳转
    BOOL isLogin=[LoginCorrelationHelper loginCorrelationHelperIsLogin];
    [[LoginCorrelationHelper shareInstance] setLoginFinishBlock:^{
        [weakSelf fBtnAction:sender];
    }];
    if (!isLogin) return;
    
    
    LoginProtocolViewController * vc = [[LoginProtocolViewController alloc]init];
    [[BaseTabBarViewController shareInstance].navigationController pushViewController:vc animated:YES];
    
}

#pragma mark--获取商品列表数据
-(void)getHomeListData{
    
    page=0;
    
    [self getHomeListPageData];
    
}

-(void)getHomeListPageData{
    
    page ++;
    isLoading = YES;
    isCanLoadMore = NO;
    
    WS(weakSelf);
    [HttpRequestHelper requestApiHomeDataTag:mTag page:page nums:row Block:^(NSString *msg, NSArray *array) {
        
        [tableView.mj_header endRefreshing];
        [tableView.mj_footer endRefreshing];
        [weakSelf stopSKV];
        [weakSelf hideHud];
        isLoading = NO;
        
        if (page == 1 && [arrayResult count] != 0)
        {
            [arrayResult removeAllObjects];
            [tableView reloadData];
        }
        
        if (REQUEST_SUCCESS) {
            
            if ([array count]==row)
            {
                isCanLoadMore = YES;
                
                [tableView.mj_footer setHidden:NO];
                
            }else
            {
                [tableView.mj_footer setHidden:YES];
            }
            
            
            [arrayResult addObjectsFromArray:array];
            
            
        }else{
            
            [weakSelf showHint:msg];
        }
        
        [tableView reloadData];
        
        
    }];
    
}

#pragma mark -- 获取报名人数
- (void)getConfigureEnrollsData{
    
    WS(weakSelf);
    
    [HttpRequestHelper requestApiConfigureEnrollsBlock:^(NSString *msg, NSNumber *total) {
        
        if (REQUEST_SUCCESS) {
            
            [totalLabel setText:[NSString stringWithFormat:@"截止目前报名人数：%@人",total]];
            
        }else{
            
            [weakSelf showHint:msg];
        }
        
    }];
    
    
}


#pragma mark -- 请求幻灯数据
- (void)getBannerData{
    
    WS(weakSelf);
    
    [HttpRequestHelper requestApiBannerNums:5 Block:^(NSString *msg, NSArray *array, NSArray *arrayURL) {
        [weakSelf stopSKV];
        [weakSelf hideHud];
        
        if (REQUEST_SUCCESS) {
            
            [arrayURLSlide removeAllObjects];
            [arrayURLSlide addObjectsFromArray:arrayURL];
            [arraySlider removeAllObjects];
            [arraySlider addObjectsFromArray:array];
            sySlider.localizationImageNamesGroup = arrayURLSlide;
            
        }else{
            
            [weakSelf showHint:msg];
        }
    }];
    
    
}

#pragma mark --  点击图片回调
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    HomeSliderModel * model = arraySlider[index];
    
    //    1文章，2套系，3商城
    
    if ([model.type isEqualToString:@"news"]) {
        
        InformationDetailsViewController * vc = [[InformationDetailsViewController alloc]init];
        vc.n_id = model.data_id;
        [[BaseTabBarViewController shareInstance].navigationController pushViewController:vc animated:YES];
    }
    
    if ([model.type isEqualToString:@"teacher"]) {
        
        TeamRandomDetailsViewController * vc = [[TeamRandomDetailsViewController alloc]init];
        vc.teacher_id = model.data_id;
        [[BaseTabBarViewController shareInstance].navigationController pushViewController:vc animated:YES];
    }
    
    if ([model.type isEqualToString:@"enroll"]) {
        
        LoginProtocolViewController * vc = [[LoginProtocolViewController alloc]init];
        
        [[BaseTabBarViewController shareInstance].navigationController pushViewController:vc animated:YES];
    }
    
    
}


#pragma mark -- 更新View
- (void)setUpdateView{
    
    ConfigureModel * model = [UserCenterHelper shareInstance].configureModel;
    
    if (model) {
        
        [self initUpdateViewWithModel:model];
        
    }else{
        
        [HttpRequestHelper requestApiConfigureBlock:^(NSString *msg, ConfigureModel * fmodel) {
            
            if (REQUEST_SUCCESS) {
                
                [self initUpdateViewWithModel:fmodel];
            }
            
        }];
    }
    
}

#pragma mark -- 检查更新View
- (void)initUpdateViewWithModel:(ConfigureModel *)model{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSString *  strVer = [app_Version stringByReplacingOccurrencesOfString:@"." withString:@""];
    
    NSLog(@"strVer----%@",strVer);
    
    if ([strVer integerValue] < [model.ver integerValue]) {
        
        HomeUpdateView * updateView = [[HomeUpdateView alloc]init];
        [ApplicationDelegate.window addSubview:updateView];
        [updateView setModel:model];
        [updateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(ApplicationDelegate.window);
        }];
        
    }
    
}

#pragma mark -- 获取用户信息

- (void)getUserInfoData{
    
    NSString * token = [UserCenterHelper shareInstance].token;
    
    if (token.length == 0) {
        
        return ;
    }
    
    [HttpRequestHelper requestApiUserInfoBlock:nil];
    
}

@end
